<template>
  <div class="database-manager">
    <div class="header">
      <div class="header-left">
        <div class="back-button">
          <el-button @click="handleBack" text>
            <el-icon><ArrowLeft /></el-icon>
            返回数据源
          </el-button>
        </div>
        <div class="title-section">
          <h3>数据库实例管理</h3>
          <span class="subtitle">数据源: {{ datasource?.name }}</span>
          <span class="count">共 {{ databases.length }} 个数据库</span>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          创建数据库
        </el-button>
        <el-button @click="handleRefresh" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索数据库名称或描述"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select v-model="statusFilter" placeholder="筛选状态" clearable style="width: 150px; margin-left: 12px;">
        <el-option label="活跃" value="active" />
        <el-option label="只读" value="readonly" />
        <el-option label="维护中" value="maintenance" />
        <el-option label="已停用" value="disabled" />
      </el-select>
      <el-select v-model="sizeFilter" placeholder="筛选大小" clearable style="width: 150px; margin-left: 12px;">
        <el-option label="小于100MB" value="small" />
        <el-option label="100MB-1GB" value="medium" />
        <el-option label="1GB-10GB" value="large" />
        <el-option label="大于10GB" value="xlarge" />
      </el-select>
    </div>

    <div class="content" v-loading="loading">
      <div v-if="filteredDatabases.length === 0" class="empty-state">
        <el-empty description="暂无数据库实例">
          <el-button type="primary" @click="handleAdd">创建第一个数据库</el-button>
        </el-empty>
      </div>
      
      <div v-else class="database-list">
        <div
          v-for="database in filteredDatabases"
          :key="database.id"
          class="database-card"
          @click="handleSelect(database)"
        >
          <div class="card-header">
            <div class="title-section">
              <h4>{{ database.name }}</h4>
              <el-tag
                :type="getStatusType(database.status)"
                size="small"
                class="status-tag"
              >
                {{ getStatusText(database.status) }}
              </el-tag>
            </div>
            <div class="actions">
              <el-dropdown @command="handleCommand" trigger="click">
                <el-button text>
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="`edit-${database.id}`">
                      <el-icon><Edit /></el-icon>
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item :command="`backup-${database.id}`">
                      <el-icon><Download /></el-icon>
                      备份
                    </el-dropdown-item>
                    <el-dropdown-item :command="`analyze-${database.id}`">
                      <el-icon><DataAnalysis /></el-icon>
                      分析
                    </el-dropdown-item>
                    <el-dropdown-item :command="`delete-${database.id}`" divided>
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          
          <div class="card-content">
            <div class="stats-row">
              <div class="stat-item">
                <el-icon class="stat-icon"><Grid /></el-icon>
                <div class="stat-info">
                  <span class="stat-value">{{ database.tables }}</span>
                  <span class="stat-label">表数量</span>
                </div>
              </div>
              <div class="stat-item">
                <el-icon class="stat-icon"><Coin /></el-icon>
                <div class="stat-info">
                  <span class="stat-value">{{ database.size }}</span>
                  <span class="stat-label">数据大小</span>
                </div>
              </div>
              <div class="stat-item">
                <el-icon class="stat-icon"><Monitor /></el-icon>
                <div class="stat-info">
                  <span class="stat-value">{{ getDatabaseTypeText(database.type) }}</span>
                  <span class="stat-label">数据库类型</span>
                </div>
              </div>
            </div>
            
            <div class="description" v-if="database.description">
              <el-icon class="desc-icon"><Document /></el-icon>
              <span>{{ database.description }}</span>
            </div>
          </div>
          
          <div class="card-footer">
            <div class="footer-left">
              <el-tag size="small" effect="plain">
                {{ database.tables }} 张表
              </el-tag>
            </div>
            <div class="footer-right">
              <el-button type="primary" size="small" @click.stop="handleSelect(database)">
                <el-icon><Right /></el-icon>
                管理表
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑数据库对话框 -->
    <el-dialog
      v-model="showDialog"
      :title="isEdit ? '编辑数据库' : '创建数据库'"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="数据库名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入数据库名称" />
        </el-form-item>
        
        <el-form-item label="字符集" prop="charset">
          <el-select v-model="form.charset" placeholder="请选择字符集" style="width: 100%;">
            <el-option label="utf8mb4" value="utf8mb4" />
            <el-option label="utf8" value="utf8" />
            <el-option label="latin1" value="latin1" />
            <el-option label="gbk" value="gbk" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="排序规则" prop="collation">
          <el-select v-model="form.collation" placeholder="请选择排序规则" style="width: 100%;">
            <el-option label="utf8mb4_unicode_ci" value="utf8mb4_unicode_ci" />
            <el-option label="utf8mb4_general_ci" value="utf8mb4_general_ci" />
            <el-option label="utf8_unicode_ci" value="utf8_unicode_ci" />
            <el-option label="utf8_general_ci" value="utf8_general_ci" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入数据库描述（可选）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  Plus,
  Refresh,
  Search,
  MoreFilled,
  Edit,
  Delete,
  Download,
  DataAnalysis,
  Grid,
  Coin,
  Monitor,
  Document,
  Right
} from '@element-plus/icons-vue'

const props = defineProps({
  databases: {
    type: Array,
    default: () => []
  },
  datasource: {
    type: Object,
    default: null
  },
  loading: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['select', 'add', 'edit', 'delete', 'refresh', 'back'])

// 搜索和筛选
const searchKeyword = ref('')
const statusFilter = ref('')
const sizeFilter = ref('')

// 对话框状态
const showDialog = ref(false)
const isEdit = ref(false)
const submitting = ref(false)

// 表单相关
const formRef = ref()
const form = ref({
  id: '',
  name: '',
  charset: 'utf8mb4',
  collation: 'utf8mb4_unicode_ci',
  description: ''
})

const rules = {
  name: [
    { required: true, message: '请输入数据库名称', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '数据库名称只能包含字母、数字和下划线，且以字母开头', trigger: 'blur' }
  ],
  charset: [
    { required: true, message: '请选择字符集', trigger: 'change' }
  ],
  collation: [
    { required: true, message: '请选择排序规则', trigger: 'change' }
  ]
}

// 计算属性
const filteredDatabases = computed(() => {
  let result = props.databases

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(db =>
      db.name.toLowerCase().includes(keyword) ||
      (db.description && db.description.toLowerCase().includes(keyword))
    )
  }

  // 状态筛选
  if (statusFilter.value) {
    result = result.filter(db => db.status === statusFilter.value)
  }

  // 大小筛选
  if (sizeFilter.value) {
    result = result.filter(db => {
      const sizeInMB = parseSizeToMB(db.size)
      switch (sizeFilter.value) {
        case 'small': return sizeInMB < 100
        case 'medium': return sizeInMB >= 100 && sizeInMB < 1024
        case 'large': return sizeInMB >= 1024 && sizeInMB < 10240
        case 'xlarge': return sizeInMB >= 10240
        default: return true
      }
    })
  }

  return result
})

// 方法
const parseSizeToMB = (sizeStr) => {
  const match = sizeStr.match(/^([\d.]+)(KB|MB|GB)$/)
  if (!match) return 0
  
  const value = parseFloat(match[1])
  const unit = match[2]
  
  switch (unit) {
    case 'KB': return value / 1024
    case 'MB': return value
    case 'GB': return value * 1024
    default: return 0
  }
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleRefresh = () => {
  emit('refresh')
}

const handleBack = () => {
  emit('back')
}

const handleSelect = (database) => {
  emit('select', database)
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  showDialog.value = true
}

const handleCommand = (command) => {
  const [action, id] = command.split('-')
  const database = props.databases.find(db => db.id === id)
  
  if (!database) return
  
  switch (action) {
    case 'edit':
      handleEdit(database)
      break
    case 'backup':
      handleBackup(database)
      break
    case 'analyze':
      handleAnalyze(database)
      break
    case 'delete':
      handleDelete(database)
      break
  }
}

const handleEdit = (database) => {
  isEdit.value = true
  form.value = { ...database }
  showDialog.value = true
}

const handleDelete = (database) => {
  emit('delete', database)
}

const handleBackup = (database) => {
  ElMessage.info(`备份数据库 "${database.name}" 功能开发中...`)
}

const handleAnalyze = (database) => {
  ElMessage.info(`分析数据库 "${database.name}" 功能开发中...`)
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 模拟提交
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isEdit.value) {
      emit('edit', form.value)
    } else {
      emit('add', form.value)
    }
    
    showDialog.value = false
    ElMessage.success(isEdit.value ? '数据库更新成功' : '数据库创建成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  form.value = {
    id: '',
    name: '',
    charset: 'utf8mb4',
    collation: 'utf8mb4_unicode_ci',
    description: ''
  }
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const getStatusType = (status) => {
  const statusMap = {
    active: 'success',
    readonly: 'warning',
    maintenance: 'info',
    disabled: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    active: '活跃',
    readonly: '只读',
    maintenance: '维护中',
    disabled: '已停用'
  }
  return statusMap[status] || '未知'
}

const getDatabaseTypeText = (type) => {
  const typeMap = {
    mysql: 'MySQL',
    postgresql: 'PostgreSQL',
    sqlserver: 'SQL Server',
    oracle: 'Oracle'
  }
  return typeMap[type] || type
}
</script>

<style scoped>
.database-manager {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left {
  flex: 1;
}

.back-button {
  margin-bottom: 8px;
}

.title-section h3 {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.subtitle {
  color: #606266;
  font-size: 14px;
  margin-right: 12px;
}

.count {
  color: #909399;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 12px;
}

.search-bar .el-input {
  flex: 1;
  min-width: 200px;
}

.content {
  flex: 1;
  overflow: auto;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.database-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.database-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.database-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.title-section h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.status-tag {
  margin-left: 8px;
}

.card-content {
  margin-bottom: 16px;
}

.stats-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.stat-item {
  display: flex;
  align-items: center;
  flex: 1;
}

.stat-icon {
  color: #409eff;
  margin-right: 8px;
  font-size: 18px;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-value {
  color: #303133;
  font-weight: 600;
  font-size: 14px;
}

.stat-label {
  color: #909399;
  font-size: 12px;
}

.description {
  display: flex;
  align-items: flex-start;
  font-size: 14px;
  color: #606266;
  line-height: 1.4;
}

.desc-icon {
  color: #909399;
  margin-right: 8px;
  margin-top: 2px;
  flex-shrink: 0;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.footer-left {
  flex: 1;
}

.footer-right {
  flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .database-manager {
    padding: 16px;
  }
  
  .header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .header-right {
    justify-content: center;
  }
  
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-bar .el-input {
    min-width: auto;
  }
  
  .database-list {
    grid-template-columns: 1fr;
  }
  
  .stats-row {
    flex-direction: column;
    gap: 8px;
  }
  
  .card-footer {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
}
</style>